<template>
	<view class="notification-container">
		<view class="notification-list" v-if="notifications && notifications.length > 0">
			<view class="list-item" v-for="(item, index) in notifications" :key="index">
				<!-- 左侧消息类型 -->
				<view class="item-left">
					<view  class="item-type" :style="{backgroundColor: item.type === 'sign' ? '#1890ff' : '#52c41a'}">
						<text class="type-text">{{ item.type === 'sign' ? '签到' : '请假' }}</text>
					</view>
		        </view>
		    
		        <!-- 右侧消息内容 -->
		        <view class="item-right">
					<!-- 签到 -->
					<view class="item-attendance" v-if="item.type === 'sign'" @click="gotoCheckin">
						<view class="item-head">
							<text class="item-name">课程: {{ item.course }}</text>
						    <text class="status-tag" :style="getStatusStyle(item.status, item.type)">{{ formatStatus(item.status, item.type) }}</text>
						</view>
						<text class="item-time">签到开始时间: {{ item.startTime.replace('T', ' ').slice(0, 16) }}</text>
						<text class="item-time">签到结束时间: {{ item.endTime.replace('T', ' ').slice(0, 16) }}</text>
					</view>
					
					<!-- 请假 -->
					<view class="item-sickapply" v-if="item.type === 'leave'" @click="gotoTeacherapproval(item)">
						<view class="item-head">
							<text class="item-name">请假原因: {{ item.message}}</text>
							<text class="status-tag" :style="getStatusStyle(item.status, item.type)">{{ formatStatus(item.status, item.type) }}</text>
						</view>
						<text class="item-time">请假开始时间: {{ item.startTime.replace('T', ' ').slice(0, 16) }}</text>
						<text class="item-time">请假结束时间: {{ item.endTime.replace('T', ' ').slice(0, 16) }}</text>
					</view>
		        </view>
		    </view>
		</view>
		
		<view class="no-message" v-if="!notifications || notifications.length === 0">
			<image src="/static/images/nomessage.jpg" class="nomessage-image"></image>
			<text>暂无消息 ~</text>
		</view>

		<!-- 底部导航栏 -->
		<view class="tab-bar">
			<view 
			  class="tab-item" 
			  :class="{active: currentTab === 0}" 
			  @click="switchTab(0)"
			>
				<text class="cuIcon cuIcon-home"></text>
				<text class="tab-text">首页</text> 
			</view>
			<view 
			  class="tab-item" 
			  :class="{active: currentTab === 1}" 
			  @click="switchTab(1)"
			>
				<text class="cuIcon cuIcon-form"></text>
				<text class="tab-text">申请</text>
			</view>
			<view 
			  class="tab-item" 
			  :class="{active: currentTab === 2}" 
			  @click="switchTab(2)"
			>
				<text class="cuIcon cuIcon-message"></text>
				<text class="tab-text">消息</text>
			</view>
			<view 
			  class="tab-item" 
			  :class="{active: currentTab === 3}" 
			  @click="switchTab(3)"
			>
				<text class="cuIcon cuIcon-my"></text>
				<text class="tab-text">我的</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			currentTab: 2,
			userInfo: {},
			notifications: [] ,//获取到的数据
		}
	},
	onShow() {
		this.checkLoginStatus()
		console.log(this.userInfo);
		this.fetchNotificationList()
	},
	onLoad() {
	  // 确保 userType 被正确初始化
	  const userInfo = uni.getStorageSync('userInfo');
	  if (userInfo) {
	    this.userType = userInfo.type || 0; // 默认为学生
	  }
	  
	  uni.$on('updateUserType', (res) => {
	    this.userType = res.type;
	    this.initDynamicConfig();
	    this.initFromLocalStorage();
	  });
	  this.initDynamicConfig();
	},
	methods: {
		//模拟数据
		mockNotificationList (userId, role) {
		  // 用户班级关联关系
		  const userClassMap = {
		    2023000000000: 2301,  // 学生张三 -> 计算机23级1班
		    2023000000001: 2301,  // 学生李四 -> 计算机23级1班
		    2023111111111: 2301   // 王老师 -> 计算机23级1班
		  };
		
		  // 模拟数据库（包含10+条测试数据）
		  const baseData = {
		    signList: [
		      // 计算机23级1班签到（王老师）
		      {
		        checkinId: 1001,
		        classId: 2301,
		        course: "计算机网络",
		        checkType: "code",
		        checkCode: "A1B2C3",
		        duration: 10,
		        enableLocation: true,
		        teacherId: 2023111111111,
		        startTime: "2024-05-20T08:00:00",
		        endTime: "2024-05-20T08:10:00",
				attendanceTime: "2024-05-20T08:03:21" // 实际签到时间
		      },
		      {
		        checkinId: 1002,
		        classId: 2301,
		        course: "数据结构",
		        checkType: "qrcode",
		        checkCode: "",
		        duration: 15,
		        enableLocation: false,
		        teacherId: 2023111111111,
		        startTime: "2024-05-21T10:30:00",
		        endTime: "2024-05-21T10:45:00",
				attendanceTime: "2024-05-21T10:30:07" // 实际签到时间
		      },
		      {
		        checkinId: 1003,
		        classId: 2301,
		        course: "操作系统",
		        checkType: "code",
		        checkCode: "X9Y8Z7",
		        duration: 20,
		        enableLocation: true,
		        teacherId: 2023111111111,
		        startTime: "2024-05-22T14:00:00",
		        endTime: "2024-05-22T14:20:00",
				attendanceTime: ""
		      },
		      {
		        checkinId: 1004,
		        classId: 2301,
		        course: "数据库原理",
		        checkType: "qrcode",
		        checkCode: "",
		        duration: 15,
		        enableLocation: true,
		        teacherId: 2023111111111,
		        startTime: new Date().toISOString(), // 进行中签到
		        endTime: new Date(Date.now() + 15*60000).toISOString(),
				attendanceTime: ""
		      },
		      // 历史签到
		      {
		        checkinId: 1005,
		        classId: 2301,
		        course: "编译原理",
		        checkType: "code",
		        checkCode: "B3C4D5",
		        duration: 25,
		        enableLocation: false,
		        teacherId: 2023111111111,
		        startTime: "2024-05-18T09:00:00",
		        endTime: "2024-05-18T09:25:00",
				attendanceTime: ""
		      }
		    ],
		    leaveList: [
		      // 已批准假条
		      {
		        studentId: 2023000000000,
		        studentName: "张三",
		        status: 1,
		        applyTime: "2024-05-19T09:15:00",
		        startTime: "2024-05-20T08:00:00",
		        endTime: "2024-05-21T18:00:00",
		        message: "病假申请",
		        teacherId: 2023111111111,
		        teacherName: "王老师",
		        classId: 2301,
		        className: "计算机23级1班",
		        approvalTime: "2024-05-19T15:30:00"
		      },
		      {
		        studentId: 2023000000000,
		        studentName: "张三",
		        status: 1,
		        applyTime: "2024-05-22T10:00:00",
		        startTime: "2024-05-23T08:00:00",
		        endTime: "2024-05-24T18:00:00",
		        message: "学术会议请假",
		        teacherId: 2023111111111,
		        teacherName: "王老师",
		        classId: 2301,
		        className: "计算机23级1班",
		        approvalTime: "2024-05-22T14:15:00"
		      },
		      // 已驳回假条
		      {
		        studentId: 2023000000000,
		        studentName: "张三",
		        status: 2,
		        applyTime: "2024-05-20T13:00:00",
		        startTime: "2024-05-21T08:00:00",
		        endTime: "2024-05-21T12:00:00",
		        message: "比赛请假",
		        teacherId: 2023111111111,
		        teacherName: "王老师",
		        classId: 2301,
		        className: "计算机23级1班",
		        approvalTime: "2024-05-20T16:45:00"
		      }
		    ]
		  };
		
		  // 根据角色过滤数据
		  return {
		    code: 200,
		    message: "查询成功",
		    data: role === 0 ? {
		      // 学生数据：本班签到 + 自己假条
		      signList: baseData.signList.filter(
		        item => item.classId === userClassMap[userId]
		      ),
		      // 修改学生假条过滤逻辑
		      leaveList: baseData.leaveList
		    } : {
		      // 教师数据：自己发起的签到 + 需要审批的假条(???)
		      signList: [{
		        checkinId: 1003,
		        classId: 2301,
		        course: "操作系统",
		        checkType: "code",
		        checkCode: "X9Y8Z7",
		        duration: 20,
		        enableLocation: true,
		        teacherId: 2023111111111,
		        startTime: "2024-05-22T14:00:00",
		        endTime: "2024-05-22T14:20:00",
				attendanceTime: ""
		      },
		      {
		        checkinId: 1004,
		        classId: 2301,
		        course: "数据库原理",
		        checkType: "qrcode",
		        checkCode: "",
		        duration: 15,
		        enableLocation: true,
		        teacherId: 2023111111111,
		        startTime: new Date().toISOString(), // 进行中签到
		        endTime: new Date(Date.now() + 15*60000).toISOString(),
				attendanceTime: ""
		      }],
			  leaveList:[]
		      // leaveList: baseData.leaveList.filter(
		      //   item => item.teacherId === userId && item.status === 0
		      // )???
		    }
		  };
		},
	
		// ---------------------------------------------------------------------------
		checkLoginStatus() {
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				uni.redirectTo({ url: '/pages/login/login' })
				return
			}
			this.userInfo = {
				name: userInfo.name,
				userId: userInfo.id,
				role: userInfo.roleName,
				userType: userInfo.type || 0
			}
		},
		
		//获取页面数据
		async fetchNotificationList(){
			uni.showLoading({ title:"获取数据中" })
			try{
				const res = await this.mockNotificationList(this.userInfo.userId , this.userInfo.userType)
				if(res.code === 200){
					uni.showToast({
						title:res.message || "获取数据成功",
						icon:'none',
						duration:2000
					})
					this.processData(res.data.signList,res.data.leaveList)
				}
			}catch(err){
				uni.showToast({
					title:'获取数据失败',
					icon:'none',
					duration:2000
				})
			}finally{
				uni.hideLoading()
			}
		},
		
		//处理获取到的数据
		processData(signList, leaveList) {
			// 处理签到的数据
			const processedSigns = signList.map(sign => {
		    // 添加类型标识
		    const item = { ...sign, type: 'sign' }
		    // 计算签到状态（根据当前时间判断）
		    const now = new Date()
		    const start = new Date(item.startTime)
		    const end = new Date(item.endTime)
			if(this.userInfo.userType === 1){
				// 老师
				if(now < end){
					item.status = 1 // 进行中
				} else {
					item.status = 2 // 已结束
				}
			}else{
				// 学生
				if (item.attendanceTime && item.attendanceTime !=='') {
					item.status = 3 // 签到成功
				} else if (now < end) {
					item.status = 1 // 进行中
				} else {
					item.status = 2 // 已结束
				}
			}
		    return item
		  })
		  // 处理假条数据
		  const processedLeaves = leaveList.map(leave => {
		    // 添加类型标识和状态转换
		    const item = { ...leave, type: 'leave'}
		    return item
		  })
		  // 合并数据并按时间降序排序
		  this.notifications = [...processedSigns, ...processedLeaves]
		    .sort((a, b) => {
		      return new Date(b.approvalTime || b.startTime) - new Date(a.approvalTime || a.startTime)
		    })
		},
		
		switchTab(index) {
		  this.currentTab = index;
		  
		  // 动态生成路由表
		  const routes = [
		    this.userType === 2 ? '/pages/teacher/teacher' : '/pages/student/student',
		    '/pages/application/list',
		    '/pages/notification/list',
		    '/pages/user/profile'
		  ];
		  
		  // 添加跳转保护
		  if (index >= routes.length) {
		    uni.showToast({
		      title: '功能正在开发中',
		      icon: 'none'
		    });
		    return;
		  }
		  
		  uni.navigateTo({
		        url: routes[index],
		        success: () => {
		          console.log('路由跳转成功:', routes[index]);
		        },
		        fail: (err) => {
		          console.error('路由跳转失败:', err);
		          uni.showToast({
		            title: '页面加载失败',
		            icon: 'none'
		          });
		        }
		      });
		},
		// 学生跳转到签到
		gotoCheckin(){
			if(this.userInfo.userType === 0){
				uni.navigateTo({
					url:"/pages/attendance/checkin"
			    })
			}
		},
		
		//跳转到显示假条详情的页面
		gotoTeacherapproval(item){
			uni.navigateTo({
				url:`/pages/application/teacherApproval?studentApplyInfo=${JSON.stringify(item)}`
			})
		},
		
		formatStatus(status, type) {
			const statusMap = {
				sign: { 1: '进行中', 2: '已结束' , 3: '签到成功'},
				leave: { 1: '已批准', 2: '已驳回' }
			}
			return statusMap[type][status] || '未知'
		},
		
		//对应状态的样式
		getStatusStyle(status, type) {
			const styles = {
				sign: {
					1: { backgroundColor: '#e8f5e9', color: '#2e7d32' },  //进行中
					2: { backgroundColor: '#f5f5f5', color: '#9e9e9e' },  //已结束
					3: { backgroundColor: '#e0f7fa', color: '#00796b' }   //签到成功
				},
				leave: {
					1: { backgroundColor: '#e8f5e9', color: '#2e7d32' },  //批准
					2: { backgroundColor: '#ffebee', color: '#c62828' }   //驳回
				}
			}
			return styles[type][status]
		}
	}
}
</script>

<style>
	@import url("css/notification.css");
	@import url("../../components/watch-login/css/icon.css");
</style>